/* jshint esversion: 6 */
// console.log(getQuery("id"));
$(document).ready(function() {
  ifLoged();
  var page = 1;
  //评分函数对应全局对象调用
  // gdy_rating.init('#rating', {
  //     mode: 'lightHalf',
  //     num: 2.5,
  //     // select: function(num, total) {
  //     //     console.log(this);
  //     //     console.log(num + '/' + total);
  //     // }
  // });
  // //鼠标划过时执行
  // $('#rating').on('select', function(e, num, total) {
  //     console.log(num + '/' + total);
  // }).on('choosen', function(e, num, total) {
  // })
  //id
  // $.getJSON('data/hotelDetail.json', function(data) {
  // 向标注点添加标注文本
  //获取当前位置
  // var geolocation = new BMap.Geolocation();
  // geolocation.getCurrentPosition(function(r) {
  // if (this.getStatus() == BMAP_STATUS_SUCCESS) {
  //     mk = new BMap.Marker(r.point);
  //     mk.addEventListener("dragend", showInfo);
  //     mk.enableDragging(); //可拖拽
  //     getAddress(r.point);
  //     mainmap.addOverlay(mk); //把点添加到地图上
  //     mainmap.panTo(r.point);
  // } else {
  //     alert('failed' + this.getStatus());
  // }

  // function showInfo(e) {
  //     var gc = new BMap.Geocoder();
  //     gc.getLocation(e.point, function(rs) {
  //         var addComp = rs.addressComponents;
  //         var address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber; //获取地址
  //         //画图 ---》显示地址信息
  //         var label = new BMap.Label(address, { offset: new BMap.Size(20, -10) });
  //         mainmap.removeOverlay(mk.getLabel()); //删除之前的label
  //         mk.setLabel(label); //alert(e.point.lng + ", " + e.point.lat + ", "+address);
  //     });
  // }

  // function getAddress(point) {
  //     var gc = new BMap.Geocoder();
  //     gc.getLocation(point, function(rs) {
  //         var addComp = rs.addressComponents;
  //         var address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber; //获取地址
  //         var label = new BMap.Label(address, { offset: new BMap.Size(20, -10) });
  //         map.removeOverlay(mk.getLabel()); //删除之前的label
  //         mk.setLabel(label);
  //     })
  // }
  // });
  //异步加载地图API
  // function loadJScript() {
  //     var script = document.createElement("script");
  //     script.type = "text/javascript";
  //     script.src = "http://api.map.baidu.com/api?v=3.0&ak=zCDofOMdwRBbZd3gmS95PAHXSvePiuAx&callback=init";
  //     document.body.appendChild(script);
  // }

  // function init() {
  //     var map = new BMap.Map("allmap"); // 创建Map实例
  //     var point = new BMap.Point(116.404, 39.915); // 创建点坐标
  //     map.centerAndZoom(point, 15);
  //     map.enableScrollWheelZoom(); //启用滚轮放大缩小
  // }
  // window.onload = loadJScript; //异步加载地图
  // });
  var id = getQuery("id");
  var hotelName, hotelAddress, hotelPhone;
  ajaxXHR(
    "get",
    url + "v1/hotel/detail",
    function(data) {
      var hotelData = data.data.hotel;
      hotelAddress = hotelData.address.hotelName = hotelData.name;
      $(".hotelName").html(hotelData.name);
      $(".address").html(hotelData.address);
      rating.init("#rating", {
        mode: "lightEntire",
        num: hotelData.star_level
        //单选评分之后发起ajax请求
        // choosen: function(params) {
        // }
      });
      $(".commonRate").html(hotelData.overall_rating);
      $(".commentTimes").html(hotelData.comment_num + "次评论");
      $(".price").html("￥" + hotelData.price);
      // $('.hotelPic').each(function(index) {
      //     console.log(hotelData.picture[index]);
      //     // var imgsrc = url_file + hotelData.picture[index];
      //     imgsrc = 'images/hotel.jpg';
      //     $(this).attr('src', imgsrc)
      // })
      const basicinfo = hotelData.hotel_introductio;
      var content = "";
      for (let i = 0; i < basicinfo.basic_info.length; i++) {
        const e = basicinfo.basic_info[i];
        content += '<li class="fl mr20">' + e + "</li>";
      }
      hotelPhone = basicinfo.contact_way;
      for (let i = 0; i < hotelPhone.length; i++) {
        const e = hotelPhone[i];
        content += '<li class="fl mr20">' + e + "</li>";
      }
      $(".basicinfo").html(content);

      $(".detail").html(basicinfo.detail);
      const facilities = data.data.hotel.hotel_facilities;
      content = "";
      for (let i = 0; i < facilities.activity.length; i++) {
        const e = facilities.activity[i];
        content += '<li class="fl mr20">' + e + "</li>";
      }
      $(".activity").html(content);
      content = "";
      for (let i = 0; i < facilities.service_items.length; i++) {
        const e = facilities.service_items[i];
        content += '<li class="fl mr20">' + e + "</li>";
      }
      $(".service_items").html(content);
      content = "";
      for (let i = 0; i < facilities.room.length; i++) {
        const e = facilities.room[i];
        content += '<li class="fl mr20">' + e + "</li>";
      }
      $(".room").html(content);
      content = "";
      for (let i = 0; i < facilities.integrated.length; i++) {
        const e = facilities.integrated[i];
        content += '<li class="fl mr20">' + e + "</li>";
      }
      $(".integrated").html(content);
      const policy = data.data.hotel.hotel_policy;
      $(".entry_time").html(policy.entry_time);
      $(".departure_time").html(policy.departure_time);
      $(".child_policy").html(policy.child_policy);
      $(".pet_policy").html(policy.pet_policy);

      var mainmap = new BMap.Map("mainMap"); // 创建Map实例
      var point = new BMap.Point(
        data.data.hotel.location.lng,
        data.data.hotel.location.lat
      );
      mainmap.centerAndZoom(point, 22); // 初始化地图,设置中心点坐标和地图级别
      //添加地图类型控件
      mainmap.addControl(
        new BMap.MapTypeControl({
          mapTypes: [BMAP_NORMAL_MAP]
        })
      ); //普通地图
      mainmap.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的
      mainmap.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
      mainmap.addControl(
        new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_LEFT })
      );
      //标注酒店地点
      var marker = new BMap.Marker(point); // 创建标注
      mainmap.addOverlay(marker); // 将标注添加到地图中
      marker.setLabel(
        new BMap.Label(data.data.hotel.name, {
          offset: new BMap.Size(20)
        })
      );
    },
    {
      hotelId: id
    },
    "json"
  );

  const type = ["all", "praise", "negative", "picture"];
  $(".commonClass").each(function(index) {
    if (page === undefined) {
      var page = 1;
    }
    $(this).on("click", function() {
      $(this)
        .addClass("active")
        .siblings()
        .removeClass("active");
      fillData.init(
        ".pageArray",
        url + "v1/hotel/evaluate/list",
        function(data) {
          const comment = data.data.evaluate;
          var str = "",
            i,
            a = [];
          $(".commentSet").html("");
          for (i = 0; i < comment.length; i++) {
            const e = comment[i];
            // const avatarPath = e.account.avatar;
            const avatarPath = "images/shilang.jpg";
            str +=
              '<li class="commentItem clearfix "><div class="userInfo fl"><img src="' +
              avatarPath +
              '"><p class="commentUser">' +
              e.account.name +
              "</p></div>";
            a.push(e.score);
            str +=
              ' <div class="commentDiv clearfix fr"><ul class=" rating-user inb clearfix"><li class="rating-item fl " title="很不好"></li><li class="rating-item fl " title="很好"></li><li class="rating-item fl " title="一般"></li><li class="rating-item fl" title="好"></li><li class="rating-item fl" title="很好"></li></ul>';
            str +=
              '<span class="commentDate">' +
              moment(e.create_time).format("YYYY-MM-DD") +
              "</span> ";
            str +=
              ' <p class="commentContent ">' +
              e.content +
              '</p> <div class="imgContainer">';
            for (let i = 0; i < e.picture.length; i++) {
              // const imgsrc = url_file+ e.picture[i];
              const imgsrc = "images/1518510076994.jpg";
              str += '<img src="' + imgsrc + '" alt="图片无法显示！">';
            }
            str += "</div></div></li>";
          }
          $(".commentSet").append(str);
          for (let x = 0; x < i; x++) {
            $(".rating-user")
              .eq(x)
              .rating({ num: a[x] });
          }
          //do something here
        },
        {
          hotelId: id,
          limit: 3,
          page: page,
          sort: type[index]
        }
      );
    });
  });

  // $.getJSON('data/comment.json', function(data) {
  //     const comment = data.data.evaluate;
  //     var str = '',
  //         i, a = [];
  //     for (i = 0; i < comment.length; i++) {
  //         const e = comment[i];
  //         // const avatarPath = e.account.avatar;
  //         const avatarPath = 'images/shilang.jpg';
  //         str += '<li class="commentItem clearfix "><div class="userInfo fl"><img src="' + avatarPath + '"><p class="commentUser">' + e.account.name + '</p></div>';
  //         a.push(e.score);
  //         str += ' <div class="commentDiv clearfix fr"><ul class=" rating-user inb clearfix"><li class="rating-item fl " title="很不好"></li><li class="rating-item fl " title="很好"></li><li class="rating-item fl " title="一般"></li><li class="rating-item fl" title="好"></li><li class="rating-item fl" title="很好"></li></ul>'
  //         str += '<span class="commentDate">' + moment(e.create_time).format('YYYY-MM-DD') + '</span> ';
  //         str += ' <p class="commentContent ">' + e.content + '</p> <div class="imgContainer">'
  //         for (let i = 0; i < e.picture.length; i++) {
  //             // const imgsrc = url_file+ e.picture[i];
  //             const imgsrc = 'images/1518510076994.jpg'
  //             str += '<img src="' + imgsrc + '" alt="图片无法显示！">'
  //         }
  //         str += '</div></div></li>'
  //     };
  //     $('.commentSet').append(str);
  //     for (let x = 0; x < i; x++) {
  //         $('.rating-user').eq(x).rating({ num: a[x] });
  //     };

  //     // rating.init('.rating-user', {
  //     //     mode: 'lightEntire',
  //     //     num: 5
  //     // });
  // });
  fillData.init(
    ".pageArray",
    url + "v1/hotel/evaluate/list",
    function(data) {
      const comment = data.data.evaluate;
      var str = "",
        i,
        a = [];
      for (i = 0; i < comment.length; i++) {
        const e = comment[i];
        // const avatarPath = e.account.avatar;
        const avatarPath = "images/shilang.jpg";
        $(".commentSet").html("");
        str +=
          '<li class="commentItem clearfix "><div class="userInfo fl"><img src="' +
          avatarPath +
          '"><p class="commentUser">' +
          e.account.name +
          "</p></div>";
        a.push(e.score);
        str +=
          ' <div class="commentDiv clearfix fr"><ul class=" rating-user inb clearfix"><li class="rating-item fl " title="很不好"></li><li class="rating-item fl " title="很好"></li><li class="rating-item fl " title="一般"></li><li class="rating-item fl" title="好"></li><li class="rating-item fl" title="很好"></li></ul>';
        str +=
          '<span class="commentDate">' +
          moment(e.create_time).format("YYYY-MM-DD") +
          "</span> ";
        str +=
          ' <p class="commentContent ">' +
          e.content +
          '</p> <div class="imgContainer">';
        for (let i = 0; i < e.picture.length; i++) {
          // const imgsrc = url_file+ e.picture[i];
          const imgsrc = "images/1518510076994.jpg";
          str += '<img src="' + imgsrc + '" alt="图片无法显示！">';
        }
        str += "</div></div></li>";
      }
      $(".commentSet").append(str);
      for (let x = 0; x < i; x++) {
        $(".rating-user")
          .eq(x)
          .rating({ num: a[x] });
      }
    },
    {
      hotelId: id,
      limit: 3,
      page: page,
      sort: type[0]
    }
  );

  $(".hotelPic").on("click", function() {
    var $this = $(this),
      $cover = $(".bannerLeft .hotelPic");
    const src = $this.attr("src");
    $this.attr("src", $cover.attr("src"));
    $cover.attr("src", src);
  });
  $(".shareByWechat").on("click", function(e) {
    e.stopPropagation();
    $(".wechatShareContent").show();
    $("#weChatShare").attr("src", url + "v1/hotel/share"); //获取二维码
    $("body").on("click", function(e) {
      $(".wechatShareContent").hide();
    });
  });
  //存储日历开始与结束时间戳
  var startTime, endTime, duringDay, startDate, endDate;
  laydate.render({
    elem: "#fromTime", //指定元素
    format: "yyyy年M月dd日",
    min: 0, //今天起
    max: 30, //30天后
    done: function(value, date) {
      startDate = value;
      var str = date.year + "/" + date.month + "/" + date.date,
        datex = new Date(str),
        now = new Date(),
        nowTimeStamp = now.getTime();
      const days = [
        "星期日",
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六"
      ];
      $("#startDay").html(days[datex.getDay()]);
      startTime = parseInt(datex.getTime());
      if (startTime - nowTimeStamp < 86400000) {
        startTime += 86399000; //如果日期选择为今天 择将其调整至今天 23：99
      }
    }
  });
  laydate.render({
    elem: "#toTime", //指定元素
    format: "yyyy年MM月dd日",
    min: 0, //今天起
    max: 30, //30天后
    done: function(value, date) {
      endDate = value;
      var str = date.year + "/" + date.month + "/" + date.date;
      var $totalTime = $(".totalTime"),
        datey = new Date(str);
      const days = [
        "星期日",
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六"
      ];
      endTime = parseInt(datey.getTime());
      $("#endDay").html(days[datey.getDay()]);
      var duringTime = endTime - startTime;
      if (duringTime <= 0) {
        $totalTime.html("请选择入住日期以后的日期！");
      } else {
        duringDay = Math.ceil(duringTime / 86400000);
        $totalTime.html("共" + duringDay + "晚");
      }
    }
  });
  $(".search").on("click", function() {
    //判断是否选择了日期
    if (!startTime) {
      var $from = $("#fromTime");
      $from[0].focus();
      $from.attr("placeholder", "请选择日期！");
    } else if (!endTime) {
      var $to = $("#toTime");
      $to[0].focus();
      $to.attr("placeholder", "请选择日期！");
    } else {
      $(".reservation-info").show();
      ajaxXHR(
        "get",
        url + "v1/hotel/room",
        function(data) {
          var $tbody = $("#tbody");
          $tbody.html("");
          const roomList = data.data.roomList;
          let str = "",
            i;
          for (i = 0; i < roomList.length; i++) {
            const e = roomList[i];
            str +=
              "<tr><td>" +
              e.name +
              " </td><td>" +
              e.bedType +
              "</td><td>" +
              e.area +
              "M<sup>2</sup></td><td>" +
              e.wayOfInternet;
            str +=
              "</td><td>" +
              e.breakfast +
              "</td> <td>" +
              e.window +
              "</td><td>" +
              e.cancelOfRules +
              "</td>";
            str +=
              '<td><span class="totalPrice">￥' +
              e.price +
              '</span></td><td class ="reservation">';
            if (e.canCheckIn) {
              str += '<button class="reservte">预定</button></td></tr>';
            } else {
              str +=
                '<button class="reservte" disabled>已订完</button></td></tr>';
            }
          }
          $tbody.append(str);
          for (let count = 0; count < i; count++) {
            $(".reservte")
              .eq(count)
              .on("click", function() {
                var dt = {
                    hotelId: id,
                    hotelName: hotelName,
                    hotelAddress: hotelAddress,
                    hotelPhone: hotelPhone,
                    room: data.data.roomList[count],
                    startTime: startTime,
                    endTime: endTime,
                    startDay: $("#startDay").text(),
                    endDay: $("#endDay").text(),
                    startDate: startDate,
                    endDate: endDate,
                    duringDay: duringDay
                  },
                  a = JSON.stringify(dt),
                  b = encodeURIComponent(a); // 先进行url编码，将中文字符转码
                window.location.href = "newOrder.html?" + b;
              });
          }
        },
        {
          hotelId: id,
          checktime: startTime + "," + endTime
        },
        "json"
      );
      // ajaxXHR('get', url + 'v1/hotel/room', function(data) {
      //     var $tbody = $('#tbody');
      //     $tbody.html('');
      //     const roomList = data.data.roomList;
      //     let str = '';
      //     for (let i = 0; i < roomList.length; i++) {
      //         const e = roomList[i];
      //         str += '<tr><td>' + e.name + ' </td><td>' + e.bedType + '</td><td>' + e.area + 'M<sup>2</sup></td><td>' + e.wayOfInternet;
      //         str += '</td><td>' + e.breakfast + '</td> <td>' + e.window + '</td><td>' + e.cancelOfRules + '</td>';
      //         str += '<td><span class="totalPrice">￥' + e.price * duringDay + '</span></td><td class ="reservation">';
      //         if (e.canCheckIn) {
      //             str += '<button class="reservte">预定</button></td></tr>';
      //         } else {
      //             str += '<button class="reservte" disabled>已订完</button></td></tr>'
      //         }
      //     }
      //     $tbody.append(str);
      // }, {
      //     hotelId: id,
      //     checktime: startTime + ',' + endTime,
      // }, "json")
    }
  });
});
